//
//  ICChatMessageVideoCell.m
//  ICome
//
//  Created by ENN on 16/3/13.
//  Copyright © 2016年 iCom. All rights reserved.
//

#import "ICChatMessageVideoCell.h"
#import "ICMessageModel.h"
#import "UIImage+Extension.h"
#import "ICMessage.h"
#import "ICVideoManager.h"
#import "ICMediaManager.h"
#import "ZacharyPlayManager.h"
#import "ICAVPlayer.h"
#import "ICFileTool.h"

@interface ICChatMessageVideoCell ()

@property (nonatomic, strong) UIImageView *imageV;
@property (nonatomic, strong) UIImage *oglImage;
@property (nonatomic, strong) UIButton *playBtn;
@property (nonatomic, strong) MBProgressHUD *hud;
@end

@implementation ICChatMessageVideoCell


- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
    if (self = [super initWithStyle:style reuseIdentifier:reuseIdentifier]) {
        [self.contentView addSubview:self.imageV];
        [self.contentView addSubview:self.playBtn];
    }
    return self;
}

- (void)setModelFrame:(ICMessageFrame *)modelFrame
{
    [super setModelFrame:modelFrame];
    
    self.imageV.frame = modelFrame.picViewF;
    self.bubbleView.image = nil;
    self.hud.hidden = YES;
    UIImage *placeholder = nil;
    NSDictionary *lnk = [NSDictionary initWithJsonString:modelFrame.model.message.lnk];
    if (![ICTools stringEmpty:modelFrame.model.mediaPath]) {// 本地存在图片
        NSString *key =  [[modelFrame.model.mediaPath stringByDeletingPathExtension] lastPathComponent];
        NSString *path = [[ICVideoManager shareManager] videoPathWithFileName:key fileDir:kDiscvoerVideoPath];
        placeholder = [UIImage videoFramerateWithPath:path];
    } else {
        placeholder = [UIImage imageWithColor:[UIColor lightGrayColor]];
    }
    UIImage *arrowImage = [UIImage makeArrowImageWithSize:modelFrame.picViewF.size image:placeholder isSender:modelFrame.model.isSender];
    self.imageV.image = arrowImage;
   
    WEAKSELF
    [self.imageV setImageWithURL:[NSURL URLWithString:[ICTools getFileMaxImageURL:(lnk[@"id"])]]
                       placeholder:arrowImage
                           options:YYWebImageOptionSetImageWithFadeAnimation
                          progress:nil
                         transform:^UIImage * _Nullable(UIImage * _Nonnull image, NSURL * _Nonnull url) {
                             return image;
                         }
                        completion:^(UIImage * _Nullable image, NSURL * _Nonnull url, YYWebImageFromType from, YYWebImageStage stage, NSError * _Nullable error) {
                            if (image) {
                                weakSelf.oglImage = image;
                                UIImage *arrowImage = [UIImage makeArrowImageWithSize:modelFrame.picViewF.size image:image isSender:modelFrame.model.isSender];
                                weakSelf.imageV.image = arrowImage;
                            }
                        }];

    [self.playBtn mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(self.imageV.mas_centerY);
        make.centerX.equalTo(self.imageV.mas_centerX);
    }];
}


- (void)imageVClick
{
    if (self.modelFrame.model.message.fileKey == nil || self.oglImage == nil) {
        return;
    }
    [self routerEventWithName:GXRouterEventVideoTapEventName
                     userInfo:@{MessageKey : self.modelFrame,
                                @"obj" : self.imageV,
                                @"oglImage" : self.oglImage,
                                @"currentCell":self
                                }];
}

#pragma mark - videoPlay

- (void)firstPlay
{
    if (self.modelFrame.model.message.fileKey == nil) {
        return;
    }
    NSString *path   = [[ICVideoManager shareManager] videoPathWithFileName:self.modelFrame.model.message.fileKey];

    if ([ICFileTool fileExistsAtPath:path]) {
        [self reloadStart];
        self.playBtn.hidden = YES;
    } else {
        ICMessage *message = self.modelFrame.model.message;
        WEAKSELF
        NSDictionary * dic  = @{@"key": message.fileKey,
                                @"fr" : message.from,
                                @"id" : message.messageId,
                                @"to" : message.to
                                };
       
        self.hud.hidden = NO;
        self.playBtn.hidden = YES;
        [ICMessageHelper receivedVideoMessage:dic finish:^(ICMessageFrame *messageF) {
            [self.hud hideAnimated:YES];
            [weakSelf reloadStart];
        } receivedSenderByYourself:[ICMessageHelper isSenderBySelf:message.from] progress:^(NSProgress *pro) {
            self.hud.progress = pro.fractionCompleted;
        }];
    }
}

- (MBProgressHUD *)hud {
    if (!_hud) {
        _hud = [MBProgressHUD showHUDAddedTo:_imageV animated:YES];
        _hud.bezelView.alpha = 0.1;
        _hud.mode = MBProgressHUDModeAnnularDeterminate;
        _hud.hidden = YES;
    }
    return _hud;
}

-(void)reloadStart {
    WEAKSELF
    NSString *path = [[ICVideoManager shareManager] videoPathWithFileName:self.modelFrame.model.message.fileKey];
    [[ZacharyPlayManager sharedInstance] startWithLocalPath:path WithVideoBlock:^(UIImage *imageData, NSString *filePath,CGImageRef tpImage) {
        if ([filePath isEqualToString:path]) {
            UIImage *arrowImage = [UIImage makeArrowImageWithSize:weakSelf.modelFrame.picViewF.size image:imageData isSender:weakSelf.modelFrame.model.isSender];
            weakSelf.imageV.image = arrowImage;
        }
    }];
    
    [[ZacharyPlayManager sharedInstance] reloadVideo:^(NSString *filePath) {
        MAIN(^{
            if ([filePath isEqualToString:path]) {
                [weakSelf reloadStart];
            }
        });
    } withFile:path];
}

-(void)stopVideo {
    _playBtn.hidden = NO;
    NSString *path = [[ICVideoManager shareManager] videoPathWithFileName:self.modelFrame.model.message.fileKey];
    [[ZacharyPlayManager sharedInstance] cancelVideo:path];
}

-(void)dealloc {
    [[ZacharyPlayManager sharedInstance] cancelAllVideo];
}

#pragma mark - Getter

- (UIImageView *)imageV
{
    if (!_imageV) {
        _imageV = [[UIImageView alloc] init];
        _imageV.layer.masksToBounds = YES;
        _imageV.layer.cornerRadius = 5;
        _imageV.clipsToBounds = YES;
        _imageV.userInteractionEnabled = YES;
        WEAKSELF
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithActionBlock:^(id  _Nonnull sender) {
            [weakSelf imageVClick];
        }];
        [_imageV addGestureRecognizer:tap];
    }
    return _imageV;
}

- (UIButton *)playBtn
{
    if (!_playBtn) {
        _playBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [_playBtn setImage:[UIImage imageNamedFromiComeSDKBundle:@"App_video_play"] forState:UIControlStateNormal];
        [_playBtn addTarget:self action:@selector(firstPlay) forControlEvents:UIControlEventTouchUpInside];
    }
    return _playBtn;
}




@end
